package parser

import "fmt"

// Node 是所有AST节点的基础接口
type Node interface {
	String() string
}

// Statement 表示SQL语句的接口
type Statement interface {
	Node
	statement()
}

// Expression 表示表达式的接口
type Expression interface {
	Node
	expression()
}

// SelectStmt 表示SELECT语句
type SelectStmt struct {
	Targets    []Expression // SELECT目标列表
	From       []TableRef   // FROM子句
	Where      Expression   // WHERE条件
	GroupBy    []Expression // GROUP BY子句
	Having     Expression   // HAVING条件
	OrderBy    []OrderByExpr // ORDER BY子句
	Limit      Expression   // LIMIT子句
	Offset     Expression   // OFFSET子句
	Distinct   bool         // DISTINCT标志
}

func (s *SelectStmt) String() string {
	return fmt.Sprintf("SELECT %v FROM %v", s.Targets, s.From)
}

func (s *SelectStmt) statement() {}

// InsertStmt 表示INSERT语句
type InsertStmt struct {
	Table   *TableRef
	Columns []string
	Values  [][]Expression
	Select  *SelectStmt // INSERT ... SELECT
}

func (i *InsertStmt) String() string {
	return fmt.Sprintf("INSERT INTO %v", i.Table)
}

func (i *InsertStmt) statement() {}

// UpdateStmt 表示UPDATE语句
type UpdateStmt struct {
	Table *TableRef
	Set   []UpdateExpr
	Where Expression
}

func (u *UpdateStmt) String() string {
	return fmt.Sprintf("UPDATE %v SET %v", u.Table, u.Set)
}

func (u *UpdateStmt) statement() {}

// DeleteStmt 表示DELETE语句
type DeleteStmt struct {
	Table *TableRef
	Where Expression
}

func (d *DeleteStmt) String() string {
	return fmt.Sprintf("DELETE FROM %v", d.Table)
}

func (d *DeleteStmt) statement() {}

// TableRef 表示表引用
type TableRef struct {
	Name  string
	Alias string
	Joins []JoinExpr
}

func (t *TableRef) String() string {
	if t.Alias != "" {
		return fmt.Sprintf("%s AS %s", t.Name, t.Alias)
	}
	return t.Name
}

// JoinExpr 表示JOIN表达式
type JoinExpr struct {
	Type      JoinType
	Table     *TableRef
	Condition Expression
}

type JoinType int

const (
	InnerJoin JoinType = iota
	LeftJoin
	RightJoin
	FullJoin
	CrossJoin
)

func (j *JoinExpr) String() string {
	return fmt.Sprintf("JOIN %v ON %v", j.Table, j.Condition)
}

// ColumnRef 表示列引用
type ColumnRef struct {
	Table  string // 可选的表名
	Column string
}

func (c *ColumnRef) String() string {
	if c.Table != "" {
		return fmt.Sprintf("%s.%s", c.Table, c.Column)
	}
	return c.Column
}

func (c *ColumnRef) expression() {}

// Literal 表示字面量
type Literal struct {
	Value interface{}
	Type  LiteralType
}

type LiteralType int

const (
	StringLiteral LiteralType = iota
	IntegerLiteral
	FloatLiteral
	BooleanLiteral
	NullLiteral
)

func (l *Literal) String() string {
	return fmt.Sprintf("%v", l.Value)
}

func (l *Literal) expression() {}

// BinaryExpr 表示二元表达式
type BinaryExpr struct {
	Left     Expression
	Operator BinaryOp
	Right    Expression
}

type BinaryOp int

const (
	EQ BinaryOp = iota // =
	NE                 // <> or !=
	LT                 // <
	LE                 // <=
	GT                 // >
	GE                 // >=
	AND                // AND
	OR                 // OR
	PLUS               // +
	MINUS              // -
	MULTIPLY           // *
	DIVIDE             // /
	MODULO             // %
	CONCAT             // ||
	LIKE               // LIKE
	ILIKE              // ILIKE
	IN                 // IN
	NOT_IN             // NOT IN
	IS_NULL            // IS NULL
	IS_NOT_NULL        // IS NOT NULL
)

func (b *BinaryExpr) String() string {
	return fmt.Sprintf("(%v %v %v)", b.Left, b.Operator, b.Right)
}

func (b *BinaryExpr) expression() {}

// UnaryExpr 表示一元表达式
type UnaryExpr struct {
	Operator UnaryOp
	Operand  Expression
}

type UnaryOp int

const (
	NOT   UnaryOp = iota // NOT
	MINUS_UNARY          // -
	PLUS_UNARY           // +
)

func (u *UnaryExpr) String() string {
	return fmt.Sprintf("%v %v", u.Operator, u.Operand)
}

func (u *UnaryExpr) expression() {}

// FunctionCall 表示函数调用
type FunctionCall struct {
	Name     string
	Args     []Expression
	Distinct bool
	Over     *WindowSpec // 窗口函数
	Filter   Expression  // FILTER (WHERE condition) 子句
	OrderBy  []OrderByExpr // ORDER BY子句（用于聚合函数）
}

func (f *FunctionCall) String() string {
	result := fmt.Sprintf("%s(%v)", f.Name, f.Args)
	if f.Filter != nil {
		result += fmt.Sprintf(" FILTER (WHERE %v)", f.Filter)
	}
	if f.Over != nil {
		result += fmt.Sprintf(" OVER %v", f.Over)
	}
	return result
}

func (f *FunctionCall) expression() {}

// AggregateExpr 表示聚合表达式
type AggregateExpr struct {
	Name     string
	Args     []Expression
	Distinct bool
	OrderBy  []OrderByExpr
	Filter   Expression
}

func (a *AggregateExpr) String() string {
	result := a.Name + "("
	if a.Distinct {
		result += "DISTINCT "
	}
	for i, arg := range a.Args {
		if i > 0 {
			result += ", "
		}
		result += arg.String()
	}
	if len(a.OrderBy) > 0 {
		result += " ORDER BY "
		for i, order := range a.OrderBy {
			if i > 0 {
				result += ", "
			}
			result += order.String()
		}
	}
	result += ")"
	if a.Filter != nil {
		result += fmt.Sprintf(" FILTER (WHERE %v)", a.Filter)
	}
	return result
}

func (a *AggregateExpr) expression() {}

// WindowSpec 表示窗口规范
type WindowSpec struct {
	PartitionBy []Expression
	OrderBy     []OrderByExpr
	Frame       *WindowFrame
}

// WindowFrame 表示窗口框架
type WindowFrame struct {
	Type  FrameType
	Start *FrameBound
	End   *FrameBound
}

type FrameType int

const (
	RowsFrame FrameType = iota
	RangeFrame
)

type FrameBound struct {
	Type   BoundType
	Offset Expression
}

type BoundType int

const (
	UnboundedPreceding BoundType = iota
	CurrentRow
	UnboundedFollowing
	Preceding
	Following
)

// OrderByExpr 表示ORDER BY表达式
type OrderByExpr struct {
	Expr      Expression
	Direction OrderDirection
	Nulls     NullsOrder
}

type OrderDirection int

const (
	ASC OrderDirection = iota
	DESC
)

type NullsOrder int

const (
	NullsDefault NullsOrder = iota
	NullsFirst
	NullsLast
)

func (o *OrderByExpr) String() string {
	return fmt.Sprintf("%v %v", o.Expr, o.Direction)
}

// UpdateExpr 表示UPDATE SET表达式
type UpdateExpr struct {
	Column string
	Value  Expression
}

func (u *UpdateExpr) String() string {
	return fmt.Sprintf("%s = %v", u.Column, u.Value)
}

// SubqueryExpr 表示子查询表达式
type SubqueryExpr struct {
	Select *SelectStmt
}

func (s *SubqueryExpr) String() string {
	return fmt.Sprintf("(%v)", s.Select)
}

func (s *SubqueryExpr) expression() {}

// ExistsExpr 表示EXISTS表达式
type ExistsExpr struct {
	Subquery *SubqueryExpr
}

func (e *ExistsExpr) String() string {
	return fmt.Sprintf("EXISTS %v", e.Subquery)
}

func (e *ExistsExpr) expression() {}

// InExpr 表示IN表达式
type InExpr struct {
	Expr     Expression
	List     []Expression // IN (value1, value2, ...)
	Subquery *SubqueryExpr // IN (SELECT ...)
	Not      bool         // NOT IN
}

func (i *InExpr) String() string {
	if i.Not {
		if i.Subquery != nil {
			return fmt.Sprintf("%v NOT IN %v", i.Expr, i.Subquery)
		}
		return fmt.Sprintf("%v NOT IN (%v)", i.Expr, i.List)
	}
	if i.Subquery != nil {
		return fmt.Sprintf("%v IN %v", i.Expr, i.Subquery)
	}
	return fmt.Sprintf("%v IN (%v)", i.Expr, i.List)
}

func (i *InExpr) expression() {}

// BetweenExpr 表示BETWEEN表达式
type BetweenExpr struct {
	Expr  Expression
	Lower Expression
	Upper Expression
	Not   bool // NOT BETWEEN
}

func (b *BetweenExpr) String() string {
	if b.Not {
		return fmt.Sprintf("%v NOT BETWEEN %v AND %v", b.Expr, b.Lower, b.Upper)
	}
	return fmt.Sprintf("%v BETWEEN %v AND %v", b.Expr, b.Lower, b.Upper)
}

func (b *BetweenExpr) expression() {}

// TypeCastExpr 表示类型转换表达式
type TypeCastExpr struct {
	Expr Expression
	Type *TypeName
}

func (t *TypeCastExpr) String() string {
	return fmt.Sprintf("%v::%v", t.Expr, t.Type)
}

func (t *TypeCastExpr) expression() {}

// IsNullExpr 表示IS NULL/IS NOT NULL表达式
type IsNullExpr struct {
	Expr Expression
	Not  bool // IS NOT NULL
}

func (i *IsNullExpr) String() string {
	if i.Not {
		return fmt.Sprintf("%v IS NOT NULL", i.Expr)
	}
	return fmt.Sprintf("%v IS NULL", i.Expr)
}

func (i *IsNullExpr) expression() {}

// LikeExpr 表示LIKE/ILIKE表达式
type LikeExpr struct {
	Expr    Expression
	Pattern Expression
	Escape  Expression // ESCAPE子句，可选
	Not     bool       // NOT LIKE
	ILike   bool       // ILIKE vs LIKE
}

func (l *LikeExpr) String() string {
	op := "LIKE"
	if l.ILike {
		op = "ILIKE"
	}
	if l.Not {
		op = "NOT " + op
	}
	if l.Escape != nil {
		return fmt.Sprintf("%v %s %v ESCAPE %v", l.Expr, op, l.Pattern, l.Escape)
	}
	return fmt.Sprintf("%v %s %v", l.Expr, op, l.Pattern)
}

func (l *LikeExpr) expression() {}

// RowExpr 表示行构造器表达式
type RowExpr struct {
	Exprs []Expression
}

func (r *RowExpr) String() string {
	return fmt.Sprintf("ROW(%v)", r.Exprs)
}

func (r *RowExpr) expression() {}

// ArraySliceExpr 表示数组切片表达式
type ArraySliceExpr struct {
	Array Expression
	Lower Expression // 可选
	Upper Expression // 可选
}

func (a *ArraySliceExpr) String() string {
	if a.Lower != nil && a.Upper != nil {
		return fmt.Sprintf("%v[%v:%v]", a.Array, a.Lower, a.Upper)
	} else if a.Lower != nil {
		return fmt.Sprintf("%v[%v:]", a.Array, a.Lower)
	} else if a.Upper != nil {
		return fmt.Sprintf("%v[:%v]", a.Array, a.Upper)
	}
	return fmt.Sprintf("%v[:]", a.Array)
}

func (a *ArraySliceExpr) expression() {}

// CoalesceExpr 表示COALESCE表达式
type CoalesceExpr struct {
	Exprs []Expression
}

func (c *CoalesceExpr) String() string {
	return fmt.Sprintf("COALESCE(%v)", c.Exprs)
}

func (c *CoalesceExpr) expression() {}

// NullIfExpr 表示NULLIF表达式
type NullIfExpr struct {
	Expr1 Expression
	Expr2 Expression
}

func (n *NullIfExpr) String() string {
	return fmt.Sprintf("NULLIF(%v, %v)", n.Expr1, n.Expr2)
}

func (n *NullIfExpr) expression() {}

// GreatestExpr 表示GREATEST表达式
type GreatestExpr struct {
	Exprs []Expression
}

func (g *GreatestExpr) String() string {
	return fmt.Sprintf("GREATEST(%v)", g.Exprs)
}

func (g *GreatestExpr) expression() {}

// LeastExpr 表示LEAST表达式
type LeastExpr struct {
	Exprs []Expression
}

func (l *LeastExpr) String() string {
	return fmt.Sprintf("LEAST(%v)", l.Exprs)
}

func (l *LeastExpr) expression() {}

// CaseExpr 表示CASE表达式
type CaseExpr struct {
	Expr    Expression     // CASE后的表达式，可选
	WhenList []*WhenClause
	Else    Expression     // ELSE子句，可选
}

type WhenClause struct {
	Condition Expression
	Result    Expression
}

func (c *CaseExpr) String() string {
	return fmt.Sprintf("CASE %v WHEN %v ELSE %v END", c.Expr, c.WhenList, c.Else)
}

func (c *CaseExpr) expression() {}

// DDL语句节点定义

// CreateTableStmt 表示CREATE TABLE语句
type CreateTableStmt struct {
	Table       *TableRef
	Columns     []*ColumnDef
	Constraints []*TableConstraint
	IfNotExists bool
	Temporary   bool
	Unlogged    bool
	Inherits    []*TableRef
	Options     []*TableOption
}

func (c *CreateTableStmt) String() string {
	return fmt.Sprintf("CREATE TABLE %v", c.Table)
}

func (c *CreateTableStmt) statement() {}

// ColumnDef 表示列定义
type ColumnDef struct {
	Name        string
	Type        *TypeName
	Constraints []*ColumnConstraint
	Default     Expression
	Generated   *GeneratedExpr
}

func (c *ColumnDef) String() string {
	return fmt.Sprintf("%s %v", c.Name, c.Type)
}

// TypeName 表示数据类型
type TypeName struct {
	Name      string
	Size      []Expression // 类型大小参数，如VARCHAR(255)
	ArrayDims int          // 数组维度
	Timezone  bool         // 时区信息
}

func (t *TypeName) String() string {
	if len(t.Size) > 0 {
		return fmt.Sprintf("%s(%v)", t.Name, t.Size)
	}
	return t.Name
}

// ColumnConstraint 表示列约束
type ColumnConstraint struct {
	Name       string
	Type       ConstraintType
	Check      Expression
	References *ForeignKeyDef
	Generated  *GeneratedExpr
}

type ConstraintType int

const (
	NotNullConstraint ConstraintType = iota
	NullConstraint
	UniqueConstraint
	PrimaryKeyConstraint
	CheckConstraint
	ForeignKeyConstraint
	DefaultConstraint
	GeneratedConstraint
)

// TableConstraint 表示表约束
type TableConstraint struct {
	Name       string
	Type       ConstraintType
	Columns    []string
	Check      Expression
	References *ForeignKeyDef
	Deferrable bool
	Initially  DeferrableType
}

type DeferrableType int

const (
	NotDeferrable DeferrableType = iota
	DeferrableImmediate
	DeferrableDeferred
)

// ForeignKeyDef 表示外键定义
type ForeignKeyDef struct {
	Table     *TableRef
	Columns   []string
	OnDelete  ReferenceAction
	OnUpdate  ReferenceAction
	Match     MatchType
}

type ReferenceAction int

const (
	NoAction ReferenceAction = iota
	Restrict
	Cascade
	SetNull
	SetDefault
)

type MatchType int

const (
	MatchFull MatchType = iota
	MatchPartial
	MatchSimple
)

// GeneratedExpr 表示生成列表达式
type GeneratedExpr struct {
	Expr   Expression
	Stored bool // true为STORED，false为VIRTUAL
}

// TableOption 表示表选项
type TableOption struct {
	Name  string
	Value Expression
}

// AlterTableStmt 表示ALTER TABLE语句
type AlterTableStmt struct {
	Table   *TableRef
	Actions []*AlterTableAction
}

func (a *AlterTableStmt) String() string {
	return fmt.Sprintf("ALTER TABLE %v", a.Table)
}

func (a *AlterTableStmt) statement() {}

// AlterTableAction 表示ALTER TABLE操作
type AlterTableAction struct {
	Type       AlterTableActionType
	Column     *ColumnDef
	Constraint *TableConstraint
	OldName    string
	NewName    string
	IfExists   bool
}

type AlterTableActionType int

const (
	AddColumn AlterTableActionType = iota
	DropColumn
	AlterColumn
	AddConstraint
	DropConstraint
	RenameTable
	RenameColumn
	SetTablespace
	SetSchema
	OwnerTo
)

// DropTableStmt 表示DROP TABLE语句
type DropTableStmt struct {
	Tables   []*TableRef
	IfExists bool
	Cascade  bool
}

func (d *DropTableStmt) String() string {
	return fmt.Sprintf("DROP TABLE %v", d.Tables)
}

func (d *DropTableStmt) statement() {}

// CreateIndexStmt 表示CREATE INDEX语句
type CreateIndexStmt struct {
	Name        string
	Table       *TableRef
	Columns     []*IndexColumn
	Unique      bool
	Concurrent  bool
	IfNotExists bool
	Method      string // btree, hash, gin, gist等
	Where       Expression
	With        []*IndexOption
	Tablespace  string
}

func (c *CreateIndexStmt) String() string {
	return fmt.Sprintf("CREATE INDEX %s ON %v", c.Name, c.Table)
}

func (c *CreateIndexStmt) statement() {}

// IndexColumn 表示索引列
type IndexColumn struct {
	Expr      Expression
	Direction OrderDirection
	Nulls     NullsOrder
	OpClass   string
}

// IndexOption 表示索引选项
type IndexOption struct {
	Name  string
	Value Expression
}

// DropIndexStmt 表示DROP INDEX语句
type DropIndexStmt struct {
	Indexes     []string
	IfExists    bool
	Cascade     bool
	Concurrent  bool
}

func (d *DropIndexStmt) String() string {
	return fmt.Sprintf("DROP INDEX %v", d.Indexes)
}

func (d *DropIndexStmt) statement() {}

// CreateViewStmt 表示CREATE VIEW语句
type CreateViewStmt struct {
	Name        *TableRef
	Columns     []string
	Select      *SelectStmt
	Replace     bool
	Temporary   bool
	Recursive   bool
	CheckOption ViewCheckOption
	Security    ViewSecurity
}

func (c *CreateViewStmt) String() string {
	return fmt.Sprintf("CREATE VIEW %v AS %v", c.Name, c.Select)
}

func (c *CreateViewStmt) statement() {}

type ViewCheckOption int

const (
	NoCheckOption ViewCheckOption = iota
	LocalCheckOption
	CascadedCheckOption
)

type ViewSecurity int

const (
	DefinerSecurity ViewSecurity = iota
	InvokerSecurity
)

// DropViewStmt 表示DROP VIEW语句
type DropViewStmt struct {
	Views    []*TableRef
	IfExists bool
	Cascade  bool
}

func (d *DropViewStmt) String() string {
	return fmt.Sprintf("DROP VIEW %v", d.Views)
}

func (d *DropViewStmt) statement() {}

// CTE (Common Table Expression) 支持

// WithClause 表示WITH子句
type WithClause struct {
	Recursive bool
	CTEs      []*CommonTableExpr
}

func (w *WithClause) String() string {
	if w.Recursive {
		return fmt.Sprintf("WITH RECURSIVE %v", w.CTEs)
	}
	return fmt.Sprintf("WITH %v", w.CTEs)
}

// CommonTableExpr 表示公共表表达式
type CommonTableExpr struct {
	Name     string
	Columns  []string
	Query    *SelectStmt
	Search   *SearchClause
	Cycle    *CycleClause
}

func (c *CommonTableExpr) String() string {
	if len(c.Columns) > 0 {
		return fmt.Sprintf("%s(%v) AS (%v)", c.Name, c.Columns, c.Query)
	}
	return fmt.Sprintf("%s AS (%v)", c.Name, c.Query)
}

// SearchClause 表示SEARCH子句(递归CTE)
type SearchClause struct {
	Type    SearchType
	Columns []string
	SetName string
}

type SearchType int

const (
	SearchDepthFirst SearchType = iota
	SearchBreadthFirst
)

// CycleClause 表示CYCLE子句(递归CTE)
type CycleClause struct {
	Columns    []string
	SetName    string
	Using      string
	CycleValue Expression
	DefaultValue Expression
}

// 扩展SelectStmt以支持WITH子句
type SelectStmtWithCTE struct {
	*SelectStmt
	With *WithClause
}

func (s *SelectStmtWithCTE) String() string {
	if s.With != nil {
		return fmt.Sprintf("%v %v", s.With, s.SelectStmt)
	}
	return s.SelectStmt.String()
}

func (s *SelectStmtWithCTE) statement() {}

// JSONB和数组类型支持

// ArrayExpr 表示数组表达式
type ArrayExpr struct {
	Elements []Expression
	Type     *TypeName // 可选的类型转换
}

func (a *ArrayExpr) String() string {
	return fmt.Sprintf("ARRAY[%v]", a.Elements)
}

func (a *ArrayExpr) expression() {}

// ArrayAccess 表示数组访问
type ArrayAccess struct {
	Array Expression
	Index Expression
}

func (a *ArrayAccess) String() string {
	return fmt.Sprintf("%v[%v]", a.Array, a.Index)
}

func (a *ArrayAccess) expression() {}

// JSONBExpr 表示JSONB表达式
type JSONBExpr struct {
	Left     Expression
	Operator JSONBOp
	Right    Expression
}

type JSONBOp int

const (
	JSONBExtract     JSONBOp = iota // ->
	JSONBExtractText                 // ->>
	JSONBPath                        // #>
	JSONBPathText                    // #>>
	JSONBContains                    // @>
	JSONBContainedBy                 // <@
	JSONBExists                      // ?
	JSONBExistsAny                   // ?|
	JSONBExistsAll                   // ?&
	JSONBConcat                      // ||
	JSONBDelete                      // -
	JSONBDeletePath                  // #-
)

func (j *JSONBExpr) String() string {
	return fmt.Sprintf("%v %v %v", j.Left, j.Operator, j.Right)
}

func (j *JSONBExpr) expression() {}

// RETURNING子句支持

// ReturningClause 表示RETURNING子句
type ReturningClause struct {
	Exprs []Expression
}

func (r *ReturningClause) String() string {
	return fmt.Sprintf("RETURNING %v", r.Exprs)
}

// 扩展DML语句以支持RETURNING

// InsertStmtWithReturning 表示带RETURNING的INSERT语句
type InsertStmtWithReturning struct {
	*InsertStmt
	Returning *ReturningClause
}

func (i *InsertStmtWithReturning) String() string {
	if i.Returning != nil {
		return fmt.Sprintf("%v %v", i.InsertStmt, i.Returning)
	}
	return i.InsertStmt.String()
}

func (i *InsertStmtWithReturning) statement() {}

// UpdateStmtWithReturning 表示带RETURNING的UPDATE语句
type UpdateStmtWithReturning struct {
	*UpdateStmt
	Returning *ReturningClause
}

func (u *UpdateStmtWithReturning) String() string {
	if u.Returning != nil {
		return fmt.Sprintf("%v %v", u.UpdateStmt, u.Returning)
	}
	return u.UpdateStmt.String()
}

func (u *UpdateStmtWithReturning) statement() {}

// DeleteStmtWithReturning 表示带RETURNING的DELETE语句
type DeleteStmtWithReturning struct {
	*DeleteStmt
	Returning *ReturningClause
}

func (d *DeleteStmtWithReturning) String() string {
	if d.Returning != nil {
		return fmt.Sprintf("%v %v", d.DeleteStmt, d.Returning)
	}
	return d.DeleteStmt.String()
}

func (d *DeleteStmtWithReturning) statement() {}

// DCL (Data Control Language) 语句支持

// GrantStmt 表示GRANT语句
type GrantStmt struct {
	Privileges []*Privilege
	Objects    []*GrantObject
	Grantees   []string
	WithGrant  bool
	GrantedBy  string
}

func (g *GrantStmt) String() string {
	return fmt.Sprintf("GRANT %v ON %v TO %v", g.Privileges, g.Objects, g.Grantees)
}

func (g *GrantStmt) statement() {}

// RevokeStmt 表示REVOKE语句
type RevokeStmt struct {
	Privileges []*Privilege
	Objects    []*GrantObject
	Grantees   []string
	Cascade    bool
	GrantOption bool
	GrantedBy  string
}

func (r *RevokeStmt) String() string {
	return fmt.Sprintf("REVOKE %v ON %v FROM %v", r.Privileges, r.Objects, r.Grantees)
}

func (r *RevokeStmt) statement() {}

// Privilege 表示权限
type Privilege struct {
	Type    PrivilegeType
	Columns []string // 列级权限
}

type PrivilegeType int

const (
	SelectPrivilege PrivilegeType = iota
	InsertPrivilege
	UpdatePrivilege
	DeletePrivilege
	TruncatePrivilege
	ReferencesPrivilege
	TriggerPrivilege
	CreatePrivilege
	ConnectPrivilege
	TemporaryPrivilege
	ExecutePrivilege
	UsagePrivilege
	AllPrivileges
)

// GrantObject 表示授权对象
type GrantObject struct {
	Type ObjectType
	Name string
}

type ObjectType int

const (
	TableObject ObjectType = iota
	SequenceObject
	FunctionObject
	ProcedureObject
	RoutineObject
	SchemaObject
	DatabaseObject
	DomainObject
	ForeignDataWrapperObject
	ForeignServerObject
	LanguageObject
	LargeObjectObject
	TablespaceObject
	TypeObject
)

// TCL (Transaction Control Language) 语句支持

// BeginStmt 表示BEGIN/START TRANSACTION语句
type BeginStmt struct {
	IsolationLevel IsolationLevel
	ReadOnly       *bool // nil表示未指定
	Deferrable     *bool // nil表示未指定
}

func (b *BeginStmt) String() string {
	return "BEGIN"
}

func (b *BeginStmt) statement() {}

type IsolationLevel int

const (
	ReadUncommitted IsolationLevel = iota
	ReadCommitted
	RepeatableRead
	Serializable
)

// CommitStmt 表示COMMIT语句
type CommitStmt struct {
	Chain bool
}

func (c *CommitStmt) String() string {
	return "COMMIT"
}

func (c *CommitStmt) statement() {}

// RollbackStmt 表示ROLLBACK语句
type RollbackStmt struct {
	Chain      bool
	Savepoint  string // ROLLBACK TO savepoint
}

func (r *RollbackStmt) String() string {
	if r.Savepoint != "" {
		return fmt.Sprintf("ROLLBACK TO %s", r.Savepoint)
	}
	return "ROLLBACK"
}

func (r *RollbackStmt) statement() {}

// SavepointStmt 表示SAVEPOINT语句
type SavepointStmt struct {
	Name string
}

func (s *SavepointStmt) String() string {
	return fmt.Sprintf("SAVEPOINT %s", s.Name)
}

func (s *SavepointStmt) statement() {}

// ReleaseSavepointStmt 表示RELEASE SAVEPOINT语句
type ReleaseSavepointStmt struct {
	Name string
}

func (r *ReleaseSavepointStmt) String() string {
	return fmt.Sprintf("RELEASE SAVEPOINT %s", r.Name)
}

func (r *ReleaseSavepointStmt) statement() {}